package com.rdxer.core.security;


import com.rdxer.model.Account;
import com.rdxer.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author lxf
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AccountService accountService;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        var account = accountService.findByName(username);

        if (account == null) {
            if (StringUtils.isEmpty(username)) {
                throw new UsernameNotFoundException(username);
            }
            List<Account> accountList = accountService.findByNameOrId(username);
            if (accountList == null || accountList.size() == 0) {
                throw new UsernameNotFoundException(username);
            }
            if (accountList.size() > 1) {
                // TODO： 用户名 和 手机号/邮箱 同名
            }
            account = accountList.get(0);
        }
        if (account.getDisabledDate() != null) {
            throw new DisabledException("用户被禁用");
        }

        return new AppUserDetails(account);
    }
}
